package com.jack.leetcode.每日一题;

public class 顺时针打印矩阵 {

    public static void main(String[] args) {
        int[][] matrix = {
                {1,2,3},
                {4,5,6},
                {7,8,9}
        };
        int[] result = spiralOrder(matrix);
        for(Integer i:result){
            System.out.print(i+",");
        }
    }

    public static int[] spiralOrder(int[][] matrix) {
        if(matrix.length == 0){
            return new int[0];
        }
        int m = matrix.length;
        int n = matrix[0].length;
        int k = 0;
        int size = m*n;
        int[] result = new int[size];
        int l = 0, r = n-1, t = 0, b = m-1;
        while(true){
            for(int i = l;i <= r;i++){
                result[k++] = matrix[t][i];
            }
            if(++t > b) break;
            for(int i = t;i <=b;i++){
                result[k++] = matrix[i][r];
            }
            if(l > --r) break;
            for(int i=r;i>=l;i--){
                result[k++] = matrix[b][i];
            }
            if(t > --b) break;
            for(int i=b;i>=t;i--){
                result[k++] = matrix[i][l];
            }
            if(++l > r) break;
        }

        return result;
    }
}
